package com.zrwl.poscloud.core.restapi.admin.baseInfo;

import com.zrwl.poscloud.base.entity.*;
import com.zrwl.poscloud.commons.utils.*;
import com.zrwl.poscloud.core.annotion.AuthorityVerify.AuthorityVerify;
import com.zrwl.poscloud.core.annotion.OperationLogger.OperationLogger;
import com.zrwl.poscloud.commons.exception.ThrowableUtils;
import com.zrwl.poscloud.commons.validator.group.Delete;
import com.zrwl.poscloud.commons.validator.group.GetList;
import com.zrwl.poscloud.commons.validator.group.Insert;
import com.zrwl.poscloud.commons.validator.group.Update;
import com.zrwl.poscloud.xo.service.*;
import com.zrwl.poscloud.xo.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * 成绩明细 controller api类
 *
 * @author 刘思童 AutoGenerate
 * @date 2023-03-10
 */
@RestController
@Api(value = "成绩明细相关接口", tags = {"成绩明细相关接口"})
@RequestMapping("/studentScoreSubjectDetail")
@Slf4j
public class StudentScoreSubjectDetailRestApi {
    @Autowired
    private StudentScoreSubjectDetailService studentScoreSubjectDetailService;
    @Autowired
    private StudentScoreBathService studentScoreBathService;
    @Autowired
    private SysDictDataService sysDictDataService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private EmployeeService employeeService;
    @AuthorityVerify
    @ApiOperation(value = "获取成绩明细列表", notes = "获取成绩明细列表", response = String.class)
    @PostMapping("/getList")
    public String getList(@Validated({GetList.class}) @RequestBody StudentScoreSubjectDetailVO studentScoreSubjectDetailVO, BindingResult result) {
        ThrowableUtils.checkParamArgument(result);
        log.info("获取成绩明细列表: {}", studentScoreSubjectDetailVO);
        return ResultUtil.successWithData(studentScoreSubjectDetailService.getPageList(studentScoreSubjectDetailVO));
    }

    @AuthorityVerify
    @ApiOperation(value = "获取成绩明细列表", notes = "获取成绩明细列表", response = String.class)
    @PostMapping("/getAllList")
    public String getAllList(@Validated({GetList.class}) @RequestBody StudentScoreSubjectDetailVO studentScoreSubjectDetailVO, BindingResult result) {
        ThrowableUtils.checkParamArgument(result);
        log.info("获取成绩明细列表: {}", studentScoreSubjectDetailVO);
        return ResultUtil.successWithData(studentScoreSubjectDetailService.getAllList(studentScoreSubjectDetailVO));
    }

    @AuthorityVerify
    @OperationLogger(value = "新增成绩明细")
    @ApiOperation(value = "新增成绩明细", notes = "新增成绩明细", response = String.class)
    @PostMapping("/add")
    public String add(@Validated({Insert.class}) @RequestBody StudentScoreSubjectDetailVO studentScoreSubjectDetailVO, BindingResult result) {
        ThrowableUtils.checkParamArgument(result);
        log.info("新增成绩明细: {}", studentScoreSubjectDetailVO);
        StudentScoreBath studentScoreBath = studentScoreBathService.getById(studentScoreSubjectDetailVO.getBatchUid());//获取当前批次
        studentScoreSubjectDetailVO.setEmployeeCode(studentScoreSubjectDetailVO.getStudentCode());
        Employee employee = employeeService.getByCode(studentScoreSubjectDetailVO.getStudentCode());
        studentScoreSubjectDetailVO.setDeptName(deptService.getDeptByCode(employee.getCompanyCode()).getName());
        String companyName = deptService.getCompanyNameByCompanyCode(DeptUtil.getCompanyFull(DeptUtil.getCompanyShortCode(employee.getCompanyCode(), String.valueOf(Integer.parseInt(DeptUtil.getCompanyLevel(employee.getCompanyCode()))-1))));
        studentScoreSubjectDetailVO.setSuperDeptName(companyName);
        return ResultUtil.successWithDataAndMessage(studentScoreSubjectDetailService.singleImport(studentScoreSubjectDetailVO,studentScoreBath),"添加成功");
    }
    @AuthorityVerify
    @OperationLogger(value = "重新生成排名")
    @ApiOperation(value = "重新生成排名", notes = "重新生成排名", response = String.class)
    @PostMapping("/generateRank")
    public String generateRank(@Validated({Insert.class}) @RequestBody StudentScoreSubjectDetailVO studentScoreSubjectDetailVO, BindingResult result) {
        ThrowableUtils.checkParamArgument(result);
        log.info("重新生成排名: {}", studentScoreSubjectDetailVO);
        return studentScoreSubjectDetailService.generateRank(studentScoreSubjectDetailVO);
    }
    @AuthorityVerify
    @OperationLogger(value = "上传Excel")
    @ApiOperation(value = "上传Excel", notes = "上传Excel", response = String.class)
    @PostMapping("/uploadExcel")
    public String uploadExcel(@RequestParam("file") List<MultipartFile> file, @RequestParam("batchUid") String batchUid, @RequestParam("maxErrorData") int maxErrorData) {
        //1获取当前批次
        StudentScoreBath studentScoreBath = studentScoreBathService.getById(batchUid);//获取当前批次
        List<SysDictData> subjectTypeList = JsonUtils.jsonToList(JsonUtils.objectToJson(sysDictDataService.getListByDictType("subject_type").get("list")), SysDictData.class);
        //2Excel解析并判重
        List<Map<String, String>> list = new ArrayList<>();
        for (int i = 0; i < file.size(); i++) {
            MultipartFile fileO = file.get(i);
            if (fileO.isEmpty()) {
                continue;
            }
            list.addAll(ExcelUtil.ArrayList(file.get(i)));
        }
        Map<String, String> columnConfigMap = new HashMap<>();
        columnConfigMap.put("superDeptName", "上级机构");
        columnConfigMap.put("deptName", "班级");
        columnConfigMap.put("employeeName", "姓名(后缀)");
        columnConfigMap.put("employeeCode", "学号");
        List<StudentScoreSubjectDetailVO> detailList = new LinkedList<>();//返回的错误数据
        /**
         * 遍历数据并进行校验
         */
        for (int i = 0; i < list.size(); i++) {
            StudentScoreSubjectDetailVO studentScoreSubjectDetailVO = new StudentScoreSubjectDetailVO();//创建明细
            studentScoreSubjectDetailVO.setBatchUid(studentScoreBath.getUid());
            if (list.get(i).isEmpty()) {
                continue;
            }
            Map<String, String> row = list.get(i);
            //赋值给明细表
            for (Map.Entry<String, String> entry : columnConfigMap.entrySet()) {
                String name = entry.getValue();
                //赋值给明细表
                if (StringUtils.isNotEmpty(row.get(name)) && StringUtils.isNotEmpty(row.get(name).trim())) {
                    ClassUtil.setFieldValueByFieldName(entry.getKey(), studentScoreSubjectDetailVO, row.get(name));
                }
            }
            if (StringUtils.isNotEmpty(row.get("分数")) && StringUtils.isNotEmpty(row.get("分数").trim())) {
                studentScoreSubjectDetailVO.setScore(Integer.parseInt(row.get("分数")));
            }
            if (StringUtils.isNotEmpty(row.get("总分")) && StringUtils.isNotEmpty(row.get("总分").trim())) {
                studentScoreSubjectDetailVO.setFull(Integer.parseInt(row.get("总分")));
            }
            if (StringUtils.isNotEmpty(row.get("科目")) && StringUtils.isNotEmpty(row.get("科目").trim())) {
                assert subjectTypeList != null;
                for (SysDictData dictData : subjectTypeList) {
                    if (Integer.parseInt(dictData.getDictValue()) != 0 && dictData.getDictLabel().equals(row.get("科目"))) {
                        studentScoreSubjectDetailVO.setSubjectType(Integer.parseInt(dictData.getDictValue()));
                    }
                }
            }
            try {
                studentScoreSubjectDetailService.singleImport(studentScoreSubjectDetailVO,studentScoreBath);
            }catch (RuntimeException e){
                studentScoreSubjectDetailVO.setSummary(e.getMessage());
                detailList.add(studentScoreSubjectDetailVO);
            }
            if (detailList.size() >= maxErrorData) {
                break;
            }
        }
        return ResultUtil.successWithDataAndMessage(detailList, "成功导入" + (maxErrorData > list.size() ? (list.size() - detailList.size()) : (detailList.size() == 0 ? list.size() : (maxErrorData - detailList.size()))) + "条数据，失败" + detailList.size() + "条数据！");
    }

    @AuthorityVerify
    @OperationLogger(value = "修改成绩明细")
    @ApiOperation(value = "修改成绩明细", notes = "修改成绩明细", response = String.class)
    @PostMapping("/edit")
    public String edit(@Validated({Update.class}) @RequestBody StudentScoreSubjectDetailVO studentScoreSubjectDetailVO, BindingResult result) {
        ThrowableUtils.checkParamArgument(result);
        log.info("修改成绩明细: {}", studentScoreSubjectDetailVO);
        return studentScoreSubjectDetailService.edit(studentScoreSubjectDetailVO);
    }

    @AuthorityVerify
    @OperationLogger(value = "删除成绩明细")
    @ApiOperation(value = "删除成绩明细", notes = "删除成绩明细", response = String.class)
    @PostMapping("/delete")
    public String delete(@Validated({Delete.class}) @RequestBody StudentScoreSubjectDetailVO studentScoreSubjectDetailVO, BindingResult result) {
        ThrowableUtils.checkParamArgument(result);
        log.info("删除成绩明细: {}", studentScoreSubjectDetailVO);
        return studentScoreSubjectDetailService.delete(studentScoreSubjectDetailVO);
    }

}
